import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Observable } from 'rxjs';

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(private jwtService: JwtService) {}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    let token = this.extractTokenFromHeader(request);
    
    // 如果header中没有token，尝试从cookies中获取
    if (!token) {
      token = request.cookies?.access_token;
    }
    
    if (!token) {
      // 如果没有token，重定向到登录页面
      // 但是我们不能在这里直接重定向，因为守卫不应该直接处理响应
      return false;
    }
    
    try {
      const payload = this.jwtService.verify(token, { 
        secret: 'my_jwt_secret_key_348794534583957' 
      });
      // 将用户信息附加到请求对象
      request.user = payload;
      return true;
    } catch {
      return false;
    }
  }

  private extractTokenFromHeader(request: any): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}